package uk.ac.ebi.bioinvindex.dao.ejb3;

import uk.ac.ebi.bioinvindex.dao.OntologyEntryDAO;
import uk.ac.ebi.bioinvindex.model.impl.term.OntologyEntryImpl;

import java.util.List;

import org.hibernate.criterion.Restrictions;

import javax.persistence.EntityManager;

/**
 * @author nsklyar
 */
public class OntologyEntryEJB3DAO<T extends OntologyEntryImpl>
		extends AnnotatableEJB3DAO<T>
		implements OntologyEntryDAO<T> {

	protected OntologyEntryEJB3DAO() {
		super();
	}

	protected OntologyEntryEJB3DAO(Class<T> persistentClass) {
		super(persistentClass);
	}

	public OntologyEntryEJB3DAO(Class<T> persistentClass, EntityManager entityManager) {
		super(persistentClass, entityManager);
	}

	/**
	 * @param acc
	 * @return
	 */
	public T getOntologyEntryByAcc(String acc) {
		List result = getSession().createCriteria(getPersistentClass())
				.add(Restrictions.eq("acc", acc))
				.list();

		return processResult(result);
	}

	public T getOntologyEntryByAccAndRefSource( String acc, String refSourceAcc) {
		List result = getSession().createCriteria(getPersistentClass())
				.add(Restrictions.eq("acc", acc))
				.createCriteria("source")
				.add(Restrictions.eq("acc", refSourceAcc))
				.list();

		return processResult(result);
	}

	public T getByNameAndRefSource(String name, String refSourceAcc) {
		List result = getSession().createCriteria(getPersistentClass())
				.add(Restrictions.eq("name", name))
				.createCriteria("source")
				.add(Restrictions.eq("acc", refSourceAcc))
				.list();

		return processResult(result);
	}

	private T processResult(List result) {
		if (result.size() == 1) {
			return (T) result.get(0);
		} else {
			return null;
		}
	}
}
